import gameConfig from "../../../config/gameConfig";
import { mgrs } from "../../../system/OverallSystem ";
import {
    authorizeParams,
    getUserInfoParams,
    loadParams,
    loginParams,
    MiniGameApiBase,
    ModalParams,
    recordedGameScreenParams,
    toastParams
} from "../miniGameBase/miniGameApiBase";

export interface TtRewardedVideoAdParam {
    // 名称	数据类型	属性	默认值	描述
    adUnitId: string;		//required	广告位 id
}

export interface TtVideoAd {
    // 通过 load 方法主动预加载广告内容。
    // 此外，在显示广告出现问题时也可以尝试主动 load 一次。
    // 该方法返回一个 Promise，如果广告已经自动拉取成功，调用该方法返回一个 resolved Promise；
    load: () => Promise<any>;
    // 广告创建后默认是隐藏的，可以通过该方法显示广告。 该方法返回一个 Promise 对象。当广告组件正常获取素材时，该 Promise 对象会是一个 resolved Promise。当广告组件发生错误时，会是一个 rejected Promise，参数与error事件监听器获得的参数相同。
    show: () => Promise<any>;
    //绑定 load 事件的监听器，用户在手动调用 load 方法后，广告组件会预先加载。 广告组件成功拉取广告素材时会触发load事件的监听器。
    //确保监听此事件时，开发者主动调用过 load 方法。
    onLoad: (listener: Function) => void;
    // 解除绑定 load 事件的监听器。
    offLoad: (listener: Function) => void;
    //绑定 error 事件的监听器。 广告组件拉取广告素材和其他情况下如果发生错误，会触发error事件的监听器。监听器会获得一个包含errCode和errMsg属性的对象参数。
    //     errCode 详情
    onError: (listener: (error: any) => void) => void;
    //    解除绑定 error 事件的监听器。
    offError: (listener: Function) => void;
    //    绑定 close 事件的监听器。 当用户点击了 Video 广告上的关闭按钮时，会触发close事件的监听器。监听器会获得一个包含isEnded属性的对象参数，表征用户是否完整观看了视频。
    onClose: (listener: (res: { isEnded: boolean }) => void) => void;
    //解除绑定 close 事件的监听器。
    offClose: (listener: Function) => void;
    //
    destroy: () => Promise<any>;
}

const tt: any = window['tt'];
export default class TtApi extends MiniGameApiBase {






    protected m_AppId: string = "";
    protected m_Secret: string = "";

    protected m_VideoAdIdIndex: number = 0;
    protected m_VideoAdIdList: string[] = ['7c2q8jp7ckk9kelaa9'];

    protected m_BannerAdIdIndex: number = 0;
    protected m_BannerAdId: string[] = [];

    protected m_InsertAdIdIndex: number = 0;
    protected m_InsertAdId: string[] = [];


    protected m_videoAd: TtVideoAd = undefined;
    protected m_BannerAd: unknown = undefined;
    /** 录屏管理器 */
    protected m_gameRecorder: any = null;

    validAppId(): void {
        // tt.onShow((res: { query, refererInfo: { appId: string, extraData: {} } }) => {
        //     cc.log(res.refererInfo.appId,this.m_appId,"appid对比")
        //     if (res.refererInfo.appId != this.m_appId) {
        //         cc.game.end();
        //         throw '非法盗用此程序将受到法律制裁';
        //     } else {
        //         cc.log('tt APP-ID 授权成功');
        //     }
        // });
    }

    ready(): void {
        cc.log("tt-api-ready");

        this.m_gameRecorder = tt.getGameRecorderManager();

        const updateManager = tt.getUpdateManager();
        updateManager.onUpdateReady((res) => {
            tt.showModal({
                title: "更新提示",
                content: "新版本已经准备好，是否重启小游戏？",
                success: (res) => {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate();
                    }
                },
            });
        });

        updateManager.onUpdateFailed((err) => {
            // 新的版本下载失败
            console.log("版本下载失败原因", err);
            tt.showToast({
                title: "新版本下载失败，请稍后再试",
                icon: "none",
            });
        });

    }

    getUserInfo(params: getUserInfoParams): void {
        tt.getUserInfo(params);
    }

    showToast(params: toastParams): void {
        tt.showToast(params);
    }

    showLoading(params: loadParams): void {
        tt.showLoading(params);
    }

    hideLoading(): void {
        tt.hideLoading();
    }

    showModal(params: ModalParams): void {
        tt.showModal(params);
    }

    authorize(params: authorizeParams): void {
        params.success && params.success();
    }

    login(params: loginParams): void {
        tt.login(params);
    }



    getVideoAdId(): string {
        const id: string = this.m_VideoAdIdList[this.m_VideoAdIdIndex];
        this.m_VideoAdIdIndex++;
        if (this.m_VideoAdIdIndex >= this.m_VideoAdIdList.length) {
            this.m_VideoAdIdIndex = 0;
        }
        return id;
    }

    loadAndShowVideoAd(successCB: () => void, errorCB: (error: any) => void, completeCB?: () => void, reportAnalyticsExplain?: any,type ='game_use_prop'): void {
       
       if(window['GM-mode']){
            successCB();
            return
       }
       
        this.showLoading({ title: '请求中', mask: true });

        const videoAdId = this.getVideoAdId();
        cc.log('tt 视频广告', videoAdId, reportAnalyticsExplain);

        //创建 视频
        const videoAd: TtVideoAd = tt.createRewardedVideoAd({
            adUnitId: videoAdId,
        });

        //监听 视频关闭
        let onCloseVideoAd = (res) => {
            //
            videoAd.offClose(onCloseVideoAd);
            cc.log('tt 视频广告关闭', res);
            if (res && res.isEnded) {
                // 给予奖励

                successCB();
                this.reportAnalytics(type, reportAnalyticsExplain)
            } else {
                errorCB('视频中途退出');
            }
            this.hideLoading();
            completeCB && completeCB();

            if((cc.sys.platform == cc.sys.BYTEDANCE_GAME||cc.sys.platform == cc.sys.BYTEDANCE_GAME_SUB) && window['tt']){
                zs_sdk.zs_dyzt.checkVideoReport(res && res.isEnded)
                console.log('checkVideoReport')
            }
            if(mgrs().soundMgr.isPlayMusic){
                mgrs().soundMgr.playMusic(mgrs().soundMgr.shangyige);
            }
        };

        //重试
        let onTryAgain = (e: any) => {
            videoAd.load().then(() => {
                videoAd.show().then(() => {
                    this.hideLoading();
                    videoAd.onClose(onCloseVideoAd);
                }).catch((e) => {//展示异常
                    errorCB && errorCB('视频展示异常');
                    this.showToast({
                        title: '视频展示异常',
                        duration: 2000
                    })
                    this.hideLoading();
                    completeCB && completeCB();
                });
            }).catch((e) => {//加载异常
                errorCB && errorCB('视频拉取异常02');
                completeCB && completeCB();
                this.hideLoading();
                this.showToast({
                    title: '视频拉取异常',
                    duration: 2000
                })
            });
        }

        cc.log('展示一次');
        videoAd.load().then(() => {
            videoAd.show().then(() => {
                this.hideLoading();
                videoAd.onClose(onCloseVideoAd);
                //展示异常
            }).catch((e) => {
                cc.log('重试一次');
                onTryAgain(e);
            })
        }).catch((e) => {//加载异常
            errorCB && errorCB('视频拉取异常01');
            completeCB && completeCB();
            this.hideLoading();
            this.showToast({
                title: '视频拉取异常',
                duration: 1000
            })
        });
    }

    FullScreenVideoAd(){
        
    }



    getInsertAdId(): string {
        const id: string = this.m_InsertAdId[this.m_InsertAdIdIndex];
        this.m_InsertAdIdIndex++;
        if (this.m_InsertAdIdIndex >= this.m_InsertAdId.length) {
            this.m_InsertAdIdIndex = 0;
        }
        return id;
    }

    showInsertAd(onAdClose: () => void, onFailed: () => void): void {

        cc.log("加抖音 插屏 广告");

        const adId = this.getInsertAdId();
        let insertAd = tt.createInterstitialAd({
            adUnitId: adId,
        });

        insertAd.load();
        insertAd.onLoad(() => {
            console.warn('插屏广告 加载完成');

            insertAd.show().catch((err) => {
                console.warn('插屏广告 显示失败 :' + JSON.stringify(err));
                insertAd.destroy();
                insertAd = null;
                if (onFailed) {
                    onFailed();
                }
            });
        });

        insertAd.onError((err) => {
            console.warn('插屏广告 加载失败' + JSON.stringify(err));
            insertAd.destroy();
            insertAd = null;
            if (onFailed) {
                onFailed();
            }
        });

        insertAd.onClose(() => {
            console.warn('插屏广告 关闭');
            if (insertAd != null) {
                insertAd.destroy();
                insertAd = null;
            }
            if (onAdClose) {
                onAdClose();
            }
        });
    }

    getBannerAdId(): string {
        const id: string = this.m_BannerAdId[this.m_BannerAdIdIndex];
        this.m_BannerAdIdIndex++;
        if (this.m_BannerAdIdIndex >= this.m_BannerAdId.length) {
            this.m_BannerAdIdIndex = 0;
        }
        return id;
    }

    showBannerAD(node: cc.Node, successCB?: () => void, errorCB?: (error: any) => void, onCloseCB?: () => void,
        setBannerPos?: ({ screenWidth, screenHeight }: { screenWidth: any; screenHeight: any; }) => cc.Vec2): void {

    }

    hideBanner() {
        // if (this.m_BannerAd != null) {
        //     this.m_BannerAd.hide();
        // }
    }

    protected m_gameRecordDate: number = 0;
    protected m_gameRecordUrl: string = undefined;

    recordedGameScreenStart(params: recordedGameScreenParams, onStart?: (res: any) => void): void {
        this.m_gameRecordDate = Date.now();
        this.m_gameRecordUrl = null;
        this.m_gameRecorder.onStart((res) => {
            cc.log('tt 录屏开始', res);
            onStart && onStart(res);
        });
        this.m_gameRecorder.onStop((res: any) => {
            cc.log('tt 录屏结束', res.videoPath);
            this.m_gameRecordUrl = res.videoPath;
        });
        this.m_gameRecorder.start(params);
    }
    recordedGameScreenStop() {
        if (Date.now() - this.m_gameRecordDate < 3500) {
            return false;
        }
        this.m_gameRecorder.stop();
        return true;
    }
    shareRecordedGameScreen(successCb?: () => void, failCb?: (e?: any) => void): void {
        if (this.m_gameRecordUrl) {
            tt.shareAppMessage({
                channel: "video", // 转发内容类型
                title: gameConfig.GAME_NAME,
                desc: gameConfig.GAME_VIDEO_SHARE_DESC,
                extra: {
                    hashtag_list: [gameConfig.GAME_NAME],
                    videoPath: this.m_gameRecordUrl, // 可替换成录屏得到的视频地址
                    videoTopics: [gameConfig.GAME_NAME],
                    video_title: gameConfig.GAME_VIDEO_SHARE_TITLE,
                    withVideoId: true,
                    defaultBgm: 'https://v.douyin.com/JmcxWo8/',
                },
                success: (res) => {
                    // let shareGameRecord = getShareGameRecordReportData('分享成功');
                    // this.reportAnalytics(shareGameRecord.key, shareGameRecord.obj);
                    cc.log("tt 分享视频成功");
                    //
                    cc.log(res.videoId);
                    cc.log(res.shareWithShareBgmStatus); //回调参数
                    cc.log("分享视频成功 4");
                    successCb && successCb();
                },
                fail: (e) => {
                    // let shareGameRecord = getShareGameRecordReportData('分享失败');
                    // this.reportAnalytics(shareGameRecord.key, shareGameRecord.obj);
                    cc.log("tt 分享视频失败", e);
                    failCb && failCb(e)
                }
            });
        } else {
            failCb && failCb(null);
            cc.log("tt 分享视频为空");
        }
    }
    isHaveRecordedGameScreen(): boolean {
        return true;
    }

    reportAnalytics(name, data) {
        if (window['tt']) {
            console.log('埋点')
            console.log(name)
            console.log(data)
            tt.reportAnalytics(name, data);
        }
    }

    vibrateShort(long= true, type = 'medium') {
        // type: "medium"
        if (!mgrs().soundMgr.isVibration) return
        console.log('震动' + type)
        if (cc.sys.platform == cc.sys.VIVO_GAME || cc.sys.platform == cc.sys.OPPO_GAME) {
            // window['qg'].vibrateShort()
            return
        } else if (window['wx'] && window['wx'].vibrateShort) {
            if(long){
                window['wx'].vibrateLong({
                    type: type,
                    style: type,
                })
            }else{
                window['wx'].vibrateShort({
                    type: type,
                    style: type,
                })
            }

        }
    }

    shareAppMessage(title='',desc=''){
        tt.shareAppMessage({
            title: title,
            desc: desc,
            imageUrl: "",
            query: "",
            success() {
              console.log("分享成功");
            },
            fail(e) {
              console.log("分享失败");
            },
          });
    }

}